/*
 * ============================================================================
 *                   GNU Lesser General Public License
 * ============================================================================
 *
 *
 *
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
 *
 *
 *
 */
package rad.framework.jaxws;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.ws.Binding;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.handler.Handler;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.Install;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Unwrap;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.log.Log;

/**
 * @author boudyacho
 */
@Scope(ScopeType.APPLICATION)
@Install(value = false, precedence = Install.FRAMEWORK)
@AutoCreate
@BypassInterceptors
public class ClientFactory {

	@Logger
	private Log log;

	private Object client;

	private String serviceQName;

	private String wsdlLocation;

	private Class<?> serviceEndpointInterface;

	private String endpointAddress;
	
	private List<Class<Handler>> handlers = new ArrayList<Class<Handler>>();

	private String componentName;

	public String getServiceQName() {
		return serviceQName;
	}

	public void setServiceQName(String serviceQName) {
		this.serviceQName = serviceQName;
	}

	public String getWsdlLocation() {
		if (StringUtils.isEmpty(wsdlLocation)) {
			return getEndpointAddress() + "?wsdl";
		}
		return wsdlLocation;
	}

	public void setWsdlLocation(String wsdlLocation) {
		this.wsdlLocation = wsdlLocation;
	}

	public Class<?> getServiceEndpointInterface() {
		return serviceEndpointInterface;
	}

	public void setServiceEndpointInterface(Class<?> serviceEndpointInterface) {
		this.serviceEndpointInterface = serviceEndpointInterface;
	}

	public String getEndpointAddress() {
		return endpointAddress;
	}

	public void setEndpointAddress(String endpointAddress) {
		this.endpointAddress = endpointAddress;
	}

	public List<Class<Handler>> getHandlers() {
		return handlers;
	}

	public void setHandlers(List<Class<Handler>> handlers) {
		this.handlers = handlers;
	}

	@Create
	public void create(Component component) throws Exception {
		componentName = component.getName();
		
		log.info("Creating: #0", this);
		
		Service service = Service.create(resolve(getWsdlLocation()), QName
				.valueOf(getServiceQName()));
		client = service.getPort(getServiceEndpointInterface());

		Map<String, Object> requestContext = ((BindingProvider) client)
				.getRequestContext();
		requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
				getEndpointAddress());

		addHandlers(((BindingProvider) client).getBinding());
	}

	protected URL resolve(String path) throws Exception {
		if (path.startsWith("classpath:")) {
			path = path.substring(10);
			URL url = getClass().getResource(path);
			if (url == null) {
				throw new RuntimeException("Could not resolve: " + path);
			}
			return url;
		}
		return new URL(path);
	}

	protected void addHandlers(Binding binding) throws Exception {
		List<Handler> handlerChain = new ArrayList<Handler>();
		for (Class<Handler> handlerType : handlers) {
			Handler handler = handlerType.newInstance();
			handlerChain.add(handler);
			if (handler instanceof BaseHandler) {
				((BaseHandler) handler).setHandlerName(componentName
						+ handlerType.getSimpleName());
			}
		}
		binding.setHandlerChain(handlerChain);
	}

	@Unwrap
	public Object getClient() {
		return client;
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this,
				ToStringStyle.MULTI_LINE_STYLE);
	}
}
